package com.cws.project.system.user.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.cws.project.cws.course.domain.Course;
import com.cws.project.cws.course.service.ICourseService;
import com.cws.project.cws.graduation.audit.domain.GraduationAudit;
import com.cws.project.cws.graduation.audit.service.IGraduationAuditService;
import com.cws.project.cws.graduation.project.domain.GraduationProject;
import com.cws.project.cws.graduation.project.service.IGraduationProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cws.common.constant.ShiroConstants;
import com.cws.common.utils.CookieUtils;
import com.cws.common.utils.DateUtils;
import com.cws.common.utils.ServletUtils;
import com.cws.common.utils.StringUtils;
import com.cws.common.utils.text.Convert;
import com.cws.framework.config.CwsConfig;
import com.cws.framework.shiro.service.PasswordService;
import com.cws.framework.web.controller.BaseController;
import com.cws.framework.web.domain.AjaxResult;
import com.cws.project.system.config.service.IConfigService;
import com.cws.project.system.menu.domain.Menu;
import com.cws.project.system.menu.service.IMenuService;
import com.cws.project.system.user.domain.User;

/**
 * 首页 业务处理
 *
 * @author xyl
 */
@Controller
public class IndexController extends BaseController {
    @Autowired
    private IMenuService menuService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private CwsConfig cwsConfig;


    @Autowired
    private IGraduationAuditService graduationAuditService;

    @Autowired
    private ICourseService courseService;

    @Autowired
    private IGraduationProjectService graduationProjectService;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap) {
        // 取身份信息
        User user = getSysUser();
        // 根据用户id取出菜单
        List<Menu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", cwsConfig.getCopyrightYear());
        mmap.put("demoEnabled", cwsConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName())) {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap) {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password) {
        User user = getSysUser();
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password)) {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin() {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response) {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) {
        // 取身份信息
        User user = getSysUser();
        mmap.put("roleId", user.getRoleId());
        mmap.put("version", cwsConfig.getVersion());
        mmap.put("gaa", "0");
        if (user.isStudent()) {
            Course course = new Course();
            course.setStudentId(user.getUserId());
            List<Course> courses = courseService.selectStudentCourseList(course);
            //计算平均
            Double tempGpa = 0.00;
            Double tempScore = 0.00;
            Integer total = 0;
            Integer failScore = 0;
            boolean con = false;
            for (Course cours : courses) {
                if (StringUtils.equals(cours.getIsCourseEnd(), "是")) {
                    Double gpa = cours.getGpa();
                    Double score = cours.getScore();
                    if (score < 60) {
                        failScore++;
                    }
                    tempGpa += gpa;
                    tempScore += score;
                    total++;
                    con = true;
                }
            }
            if(con){
                mmap.put("gaa", "1");
                mmap.put("avgGpa", new BigDecimal(tempGpa / total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                mmap.put("avgScore", new BigDecimal(tempScore / total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                mmap.put("failScore", failScore);
            }

            //查询是否毕业审核
            GraduationAudit graduationAudit = new GraduationAudit();
            graduationAudit.setStudentId(user.getUserId());
            List<GraduationAudit> graduationAudits = graduationAuditService.selectGraduationAuditList(graduationAudit);
            if(graduationAudits.size() > 0){
                GraduationAudit ga = graduationAudits.get(0);
                if(StringUtils.isNotBlank(ga.getAuditStatus())){
                    mmap.put("auditStatus", ga.getAuditStatus());
                }
            }
        }
        return "main";
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (StringUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
